package org.pp.openapi.sql;

import org.pp.openapi.common.ApiException;
import org.pp.openapi.utils.StrUtil;

import java.util.Map;

/**
 * api SQL生成器
 */
public class OpenDataSqlProvider {
    /**
     * 查询SQL
     */
    public static final String SQL_FIELD = "_sql";

    /**
     * 增删改时使用
     */
    public static final String TABLE_FIELD = "_table";

    /**
     * 主键字段
     */
    public static final String PK_FIELD = "_pk";

    /**
     * 单条查询
     * @param params
     * @return
     */
    public String find(Map<String, String> params){
        String sql = params.get(SQL_FIELD) + " LIMIT 1";
        params.remove(SQL_FIELD);
        return sql;
    }

    /**
     * 分页查询
     * @param params
     * @return
     */
    public String select(Map<String, String> params){
        String sql = params.get(SQL_FIELD);
        params.remove(SQL_FIELD);
        return sql;
    }

    /**
     * 删除
     * @param params
     * @return
     */
    public String delete(Map<String, String> params){
        String sql = params.get(SQL_FIELD);
        params.remove(SQL_FIELD);
        return sql;
    }

    /**
     * 新增
     * @param params
     * @return
     */
    public String insert(Map<String, String> params){
        String table = params.get(TABLE_FIELD);
        params.remove(TABLE_FIELD);

        StringBuilder sb = new StringBuilder("INSERT INTO ");
        sb.append(table).append(" ( ");
        for(String f:params.keySet()){
            sb.append("`").append(f).append("`,");
        }
        sb.setLength(sb.length()-1);
        sb.append(" ) values ( ");
        for(String f:params.keySet()){
            sb.append("#{").append(f).append("},");
        }
        sb.setLength(sb.length()-1);
        sb.append(" );");
        return sb.toString();
    }

    /**
     * 更新
     * @param params
     * @return
     */
    public String update(Map<String, String> params){
        String pkField = params.get(PK_FIELD);
        if(StrUtil.isEmpty(pkField)){
            throw new ApiException("数据主键不能为空");
        }
        String table = params.get(TABLE_FIELD);
        params.remove(TABLE_FIELD);
        params.remove(PK_FIELD);

        StringBuilder sb = new StringBuilder("UPDATE ");
        sb.append(table).append(" SET ");
        for(String f:params.keySet()){
            sb.append("`").append(f).append("` = #{").append(f).append("},");
        }
        sb.setLength(sb.length()-1);
        sb.append(" WHERE ").append(pkField).append(" = #{").append(pkField).append("}");
        return sb.toString();
    }

    /**
     * 执行指定的SQL
     * @param sql
     * @return
     */
    public String exec(String sql){
        return sql;
    }

}
